package com.pwser.zk;

import java.util.ArrayList;
import java.util.List;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

public class DistributedClient {
	
	private static final String connectString = "192.168.33.102:2181,192.168.33.103:2181,192.168.33.104:2181";
	private static final int sessionTimeout = 2000;
	private static final String serversPath = "/servers";
	private ZooKeeper zkClient = null;
	//volatile表示堆内存中的list对象修改时阻止线程复制到栈内存中修改，保证对象数据同源
	private volatile List<String> serverList = null;
	
	/**
	 * 创建zk连接
	 * @throws Exception 
	 */
	public void getConnect() throws Exception {
		zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				//监听事件处理逻辑
				try {
					getServerList();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	/**
	 * 获取服务器列表
	 * @throws Exception 
	 */
	public void getServerList() throws Exception {
		List<String> childNameList = zkClient.getChildren(serversPath, true);
		List<String> newServerList = new ArrayList<String>();
		for (String childName : childNameList) {
			byte[] data = zkClient.getData(serversPath + "/" + childName , false, null);
			newServerList.add(new String(data));
		}
		serverList = newServerList;
		System.out.println("当前在线服务器：" + serverList);
	}
	
	/**
	 * 客户端业务操作
	 * @throws Exception 
	 */
	public void handleBussiness() throws Exception  {
		System.out.println("client start working...");
		Thread.sleep(Long.MAX_VALUE);
	}
	
	public static void main(String[] args) throws Exception {
		DistributedClient client = new DistributedClient();
		//创建zk连接
		client.getConnect();
		//获取服务器列表
		client.getServerList();
		//客户端业务操作
		client.handleBussiness();
	}

}
